package 二叉树;

public class LC_236二叉树的最近公共祖先 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) { val = x; }
    }
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root==null)
            return null;
        if(root.val==p.val||root.val==q.val)
            return root;
        //left
        TreeNode left=lowestCommonAncestor(root.left,p,q);
        //right
        TreeNode right=lowestCommonAncestor(root.right,p,q);
        //mid
        if(left!=null && right!=null)
            return root;
        else if(left!=null && right==null)
            return left;
        else if(left==null && right!=null)
            return right;
        else
            return null;
    }
}
